package com.industrial.white.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MybatisList2StringConvHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        String preStr = strings.stream().collect(Collectors.joining(","));
        preparedStatement.setString(i,preStr);
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String string = resultSet.getString(s);
        if(StringUtils.isNotBlank(string)){
            List<String> collect = Arrays.stream(string.split(",")).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public List<String> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String string = resultSet.getString(i);
        if(StringUtils.isNotBlank(string)){
            List<String> collect = Arrays.stream(string.split(",")).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String string = callableStatement.getString(i);
        if(StringUtils.isNotBlank(string)){
            List<String> collect = Arrays.stream(string.split(",")).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
